<template>
  <div class="articleList">
    <!-- 控制下拉是否处于加载中 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :success-text="tipText">
          <!-- v-model="loading"  控制当前是否在加载中，如果在加载中，是不会下载下一页的数据 -->
    <!-- ：finished="finished" 控制数据有没有加载完成， 如果加载完成，没有数据了， 不会再去加载下一页 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <!-- <van-cell v-for="item in list" :key="item.art_id" :title="item.title" /> -->
      <article-item :row="item" v-for="item in list" :key="item.art_id + ''" :title="item.title" />
    </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getArticleList } from '@/api/article.js'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  components: { ArticleItem },
  props: {
    channelId: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      loading: false,
      finished: false,
      timestamp: Date.now(),
      list: [],
      error: false,
      isLoading: false,
      tipText: ''
    }
  },

  created () {},

  methods: {
    // 1.进入页面，并且显示list 列表组件就会出发
    // 2.加载的数据没有占满一屏，继续加载下一页
    // 3.触底的时候
    async onLoad () {
      // 1.发送请求获取数据
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: this.timestamp,
          with_top: 1
        })
        console.log(res)

        if (Math.random() > 0.5) {
          console.lg(12)
        }
        // 2.保存数据
        this.list.push(...res.results)
        // console.log(this.list)
        this.timestamp = res.pre_timestamp
        // this.list.push(this.list.length+1)
        // 3.让当前这一状态的加载状态结束
        this.loading = false
        // 4.数据全部加载完成
        if (!res.results.length) {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () {
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: Date.now(),
          with_top: 1
        })
        if (Math.random() > 0.5) {
          console.lg(12)
        }
        // console.log(res)
        this.list.unshift(...res.results)
        this.isLoading = false
        this.tipText = '刷新成功'
      } catch (err) {
        this.isLoading = false
        this.tipText = '刷新失败，稍后重试'
      }
    }
  }
}
</script>

<style scoped lang="less">
.articleList{
  height: 80vh;
  overflow-y: scroll;
}
</style>
